package mvc.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mvc.ation.Action;
import mvc.form.ActionForm;
import mvc.form.FullForm;
import mvc.util.XmlBean;


public class DispacherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String path = request.getServletPath();
		
		Map<String,XmlBean> actionMap = (Map<String,XmlBean>)this.getServletContext().getAttribute("actionInfo");
		XmlBean xmlB = actionMap.get(this.getPath(path));
		
		String formName = xmlB.getFormName();
		String actionName = xmlB.getActionName();
		Map<String,String> pages = xmlB.getPages();
		ActionForm form = FullForm.fullForm(formName, request);
		Class clazz;
		try {
			clazz = Class.forName(actionName);
			Action action = (Action)clazz.newInstance();
			Map<String,String> maps = action.excute(form);
			String key = maps.keySet().iterator().next();
			String value = maps.get(key);
			String forwardPath = pages.get(key);
			request.setAttribute("mess", value);
		    RequestDispatcher dis = request.getRequestDispatcher(forwardPath);
		    dis.forward(request, response);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println(form.toString());
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
   
	
	private String getPath(String serveletPath){
		return serveletPath.split("\\.")[0];
	}
}
